import axios from "axios";
import {ElNotification} from "element-plus";
import {getToken, removeToken, setToken} from "@/utils/auth";
import {AdminToken} from "@/utils/constant";
import useUserStore from "@/store/modules/user";
import qs from "qs";
// 不需要token的域名白名单
const whiteList = ['/admin/login']

const request = axios.create({
    baseURL: '/api'
})

// 请求拦截器
request.interceptors.request.use(config => {
    // 判断是否为白名单，设置token
    if (!whiteList.includes(config.url)) {
        config.headers[AdminToken] = getToken(AdminToken)
    }
    if (config.method.toUpperCase() === 'GET' && config.params) {
        let url = config.url + '?' + qs.stringify(config.params, {skipNulls: true});
        config.params = {}
        config.url = url
    }
    return config
}, err => {
    return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use(res => {
    switch (res.data.code) {
        case 500:
            ElNotification({
                message: res.data.msg || '请求失败',
                type: 'error',
                duration: 1500
            });
            return Promise.reject(res.data)
        default:
            return Promise.resolve(res.data)
    }
}, err => {
    const userStore = useUserStore();
    const msg = err.response.data.msg || '请求失败'
    ElNotification({
        message: msg || '请求失败',
        type: 'error',
        duration: 1500
    })
    if (err.status === 401) {
        setTimeout(() => {
            removeToken();
            location.reload()
        }, 100)
        // userStore.logout().finally(() => {
        //     setTimeout(() => {
        //         location.reload()
        //     }, 100)
        // })
    }
    return Promise.reject(err)
})

export default request
